/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.controller;

import com.googlecode.bambole.domain.Logo;
import com.googlecode.bambole.controller.util.JsfUtil;
import com.googlecode.bambole.controller.util.PaginationUtil;
import com.googlecode.bambole.domain.User;
import com.googlecode.bambole.facade.LogoFacade;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import java.io.Serializable;
import java.util.Date;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseId;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import org.apache.commons.io.IOUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 */
@Named("logoController")
@SessionScoped
public class LogoController implements Serializable {

    private Logo current;
    private DataModel items = null;

    @EJB
    private com.googlecode.bambole.facade.LogoFacade ejbFacade;

    private PaginationUtil pagination;
    private int selectedItemIndex;
    private int recordCount;

    public LogoController() {
    }

    public Logo getSelected() {
        if (current == null) {
            current = new Logo();
        }
        return current;
    }

    public void setSelected(Logo current) {
        this.current = current;
    }

    private LogoFacade getFacade() {
        return ejbFacade;
    }

    public PaginationUtil getPagination() {
        if (pagination == null) {
            pagination = new PaginationUtil(3) {

                @Override
                public int getItemsCount() {
                    return getFacade().count(getQuery());
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, getQuery()));
                }
            };
        }
        return pagination;
    }

    public String refreshList() {
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareList() {
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareView() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        recordCount = getFacade().count(getQuery());

        return "view.xhtml?faces-redirect=true";
    }

    public String prepareCreate() {
        current = new Logo();
        return "create.xhtml?faces-redirect=true";
    }

    public String create() {

        if (!validateRecord()) {
            return null;
        }

        Date date = new Date();
        User user = (User) JsfUtil.getSessionParameter("user");
        current.setCreated(date);
        current.setCreatedBy(user);
        current.setUpdated(date);
        current.setUpdatedBy(user);

        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String prepareEdit() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));

            return null;
        }
        return "edit.xhtml?faces-redirect=true";
    }

    public String update() {

        if (!validateRecord()) {
            return null;
        }

        current.setUpdated(new Date());
        current.setUpdatedBy((User) JsfUtil.getSessionParameter("user"));

        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String destroy() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }
        performDestroy();
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public Logo getLogo(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex + pagination.getPageFirstItem();
    }

    public boolean isHasNextRecord() {
        return selectedItemIndex + 2 <= recordCount;
    }

    public boolean isHasPreviousRecord() {
        return selectedItemIndex > 0;
    }

    public String nextItem() {

        selectedItemIndex++;

        if (selectedItemIndex < recordCount) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    public String previousItem() {

        selectedItemIndex--;

        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    private boolean validateRecord() {

        boolean retVal = true;

        if (current.getLogo() == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("LogoRequired"));

            retVal = false;
        }

        if (!getFacade().isEnabledLogoUnique(current.getId() == null ? -1 : current.getId())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("EnabledLogoAlreadyExists"));

            retVal = false;
        }

        return retVal;
    }

    private String getQuery() {
        return "SELECT l FROM Logo l";
    }

    public StreamedContent getLogo() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            return new DefaultStreamedContent();
        } else {
            if (context.getExternalContext().getRequestParameterMap().get("logoId") != null) {
                current = getLogo(Integer.valueOf(context.getExternalContext().getRequestParameterMap().get("logoId")));
            }
            byte[] logo = new byte[0];
            if (current.getLogo() != null) {
                logo = current.getLogo();
            }
            return new DefaultStreamedContent(
                    new ByteArrayInputStream(logo),
                    "image");
        }
    }

    public void logoUpload(FileUploadEvent event) throws IOException {
        current.setLogo(IOUtils.toByteArray(event.getFile()
                .getInputstream()));
    }

    public void logoDestroy() {
        current.setLogo(null);
    }
}
